/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mobiwebinc.compconn.events;

import com.mobiwebinc.compconn.events.command.Command;
import com.mobiwebinc.compconn.events.command.Decoder;
import com.mobiwebinc.compconn.screen.ScreenGeometry;
import java.awt.Point;
import java.awt.event.MouseEvent;

/**
 *
 * @author suraj
 */
public class Mouse implements EventHandler {

    ScreenGeometry geometry;

    public Mouse(ScreenGeometry geometry) {
        this.geometry = geometry;
    }

    public void handleRequest(String cmd) {
//        System.out.println("cmd: " + cmd);
        if (cmd.startsWith(Command.MOUSE_UP)) {
            mouseUp(cmd);
        } else if (cmd.startsWith(Command.MOUSE_DOWN)) {
            mouseDown(cmd);
        } else if (cmd.startsWith(Command.MOUSE_MOVE)) {
            mouseMove(cmd);
        } else if (cmd.startsWith(Command.MOUSE_RELATIVE_MOVE)) {
            mouseMoveRelative(cmd);
        } else if (cmd.startsWith(Command.MOUSE_SCROLL)) {
            mouseScroll(cmd);
        }

    }

    private void switchMonitor(String cmd) {
        int[] params = Decoder.intParameters(cmd);
        geometry.switchToMonitor(params[0]);
    }

    private int button(int btn) {
        return (btn == 1) ? MouseEvent.BUTTON1_MASK : MouseEvent.BUTTON3_MASK;
    }

    private void mouseDown(String cmd) {
        int[] params = Decoder.intParameters(cmd);
        system.mousePress(button(params[0]));
    }

    private void mouseMove(String cmd) {
        int[] params = Decoder.intParameters(cmd);
        geometry.setPhonePt(new Point(params[0], params[1]));
        Point screenPt = geometry.getScreenPt();
        system.mouseMove(screenPt.x, screenPt.y);
    }

    private void mouseMoveRelative(String cmd) {
        int[] params = Decoder.intParameters(cmd);
        geometry.moveScreenPt(new Point(params[0], params[1]));
        Point screenPt = geometry.getScreenPt();
        system.mouseMove(screenPt.x, screenPt.y);
    }

    private void mouseScroll(String cmd) {
        double[] params = Decoder.doubleParameters(cmd);
        system.mouseWheel((int) params[0]);
    }

    private void mouseUp(String cmd) {
        int[] params = Decoder.intParameters(cmd);
        system.mouseRelease(button(params[0]));
    }

    public boolean isSupported(String cmd) {
        return cmd.startsWith(Command.MOUSE_PREFIX);
    }
}
